/*****************************************************************************************
**  Author:COCO 2022
*****************************************************************************************/
//此js文件是用来自定义扩展业务代码，可以扩展一些自定义页面或者重新配置生成的代码
import { h, resolveComponent, defineAsyncComponent } from 'vue';
// import modelBody from "./equip_extend/Equip_SpotMaintPlanModelBody.vue"
// import modelHeader from "./equip_extend/Equip_SpotMaintPlanModelHeader.vue"
// import modelFooter from "./equip_extend/Equip_SpotMaintPlanModelFooter.vue"
import modelBody from "./bom_extend/bommasterbody.vue"
import modelHeader from "./bom_extend/bommasterheader.vue"
import modelFooter from "./bom_extend/bommasterfooter.vue"
import { ElMessageBox, ElMessage } from 'element-plus';

let extension = {
  components: {
    //查询界面扩展组件
    gridHeader: '',
    gridBody: '',
    gridFooter: '',
    //新建、编辑弹出框扩展组件
    modelHeader: modelHeader,
    modelBody: modelBody,
    modelFooter: modelFooter
  },
  tableAction: '', //指定某张表的权限(这里填写表名,默认不用填写)
  buttons: { 
    view: [
      {
        name: '查看详情',
        icon: 'el-icon-document',
        type: 'primary',
        onClick: function(row) {
          this.viewBOMDetail(row);
        }
      }
    ], 
    box: [], 
    detail: [] 
  }, //扩展的按钮
  methods: {
     //下面这些方法可以保留也可以删除
    onInit() {  //框架初始化配置前，
        //示例：在按钮的最前面添加一个按钮
        //   this.buttons.unshift({  //也可以用push或者splice方法来修改buttons数组
        //     name: '按钮', //按钮名称
        //     icon: 'el-icon-document', //按钮图标vue2版本见iview文档icon，vue3版本见element ui文档icon(注意不是element puls文档)
        //     type: 'primary', //按钮样式vue2版本见iview文档button，vue3版本见element ui文档button
        //     onClick: function () {
        //       this.$Message.success('点击了按钮');
        //     }
        //   });

        //示例：设置修改新建、编辑弹出框字段标签的长度
        // this.boxOptions.labelWidth = 150;
        //显示序号(默认隐藏)
        this.columnIndex = true;
        this.height = this.height - 100;
        //自定义弹出框的高与宽
        this.boxOptions.height = document.body.clientHeight * 0.9;
        this.boxOptions.width = document.body.clientWidth * 0.8;
        
        // 添加查看详情方法
        this.viewBOMDetail = this.viewBOMDetail.bind(this);
        
        // 添加操作列
        this.columns.push({
            field: '操作',
            title: '操作',
            width: 120,
            align: 'center',
            formatter: (row) => {
                return '<a class="bom-detail-link" style="color: #3a8ee6;cursor: pointer;">查看详情</a>';
            },
            click: (row) => {
                console.log('点击查看详情按钮:', row);
                this.viewBOMDetail(row);
            }
        });
    },
    onInited() {
      //框架初始化配置后
      //如果要配置明细表,在此方法操作
      //this.detailOptions.columns.forEach(column=>{ });
    },
    searchBefore(param) {
      //界面查询前,可以给param.wheres添加查询参数
      //返回false，则不会执行查询
      return true;
    },
    searchAfter(result) {
      //查询后，result返回的查询数据,可以在显示到表格前处理表格的值
      return true;
    },
    addBefore(formData) {
      //新建保存前formData为对象，包括明细表，可以给给表单设置值，自己输出看formData的值
      this.setFormData(formData);
      return true;
    },
    updateBefore(formData) {
      //编辑保存前formData为对象，包括明细表、删除行的Id
      this.setFormData(formData);
      return true;
    },
    setFormData(formData) { //新建或编辑时，将从表1、2的数据提交到后台,见后台Equip_SpotMaintPlanService的新建方法
      //后台从对象里直接取extra的值
      let extra = {
        table1List: this.$refs.modelBody.$refs.table1.rowData,//获取从表1的行数据
        table2List: this.$refs.modelBody.$refs.table2.rowData//获取从表2的行数据
      }
      formData.extra = JSON.stringify(extra);
    },
    resetUpdateFormAfter() { //编辑弹出框时，点重置时，可自定义重置
      console.log('resetUpdateFormAfter')
      return true;
    },
    resetAddFormAfter() { //新建弹出框时，点重置时，可自定义重置
      console.log('resetAddFormAfter')
      return true;
    },
    rowClick({ row, column, event }) {
      //查询界面点击行事件
      // this.$refs.table.$refs.table.toggleRowSelection(row); //单击行时选中当前行;
    },
    modelOpenAfter(row) {
      //点击编辑、新建按钮弹出框后，可以在此处写逻辑，如，从后台获取数据
      //(1)判断是编辑还是新建操作： this.currentAction=='Add';
      //(2)给弹出框设置默认值
      //(3)this.editFormFields.字段='xxx';
      //如果需要给下拉框设置默认值，请遍历this.editFormOptions找到字段配置对应data属性的key值
      //看不懂就把输出看：console.log(this.editFormOptions)
      if (this.currentAction == 'Add') {
        this.editFormFields.Status = "1"
      }
      this.editFormOptions.forEach(item => {
        item.forEach(x => {
          //如果是编辑设置为只读
          if (x.field == "SpotMaintPlanCode") {
            x.placeholder = "请输入，忽略将自动生成";
          }
        })
      })
       //是否子组件渲染完成
      //新建功时，清空 清空,从表1，从表2的数据
      this.$nextTick(() => {
        //这里没有给弹出框中的表格传参，如果需要参数可以通过 this.$emit("parentCall", 获取页面的参数
        //具体见自定义页面Equip_SpotMaintPlanModelBody.vue中的modelOpen方法的使用 this.$emit("parentCall", ($this) => {
        this.$refs.modelBody.modelOpen();
      })
    },
    
    // 查看BOM详情
    viewBOMDetail(row) {
      // 创建BOM详情弹框
      this.createBOMDetailDialog(row);
    },
    
    // 创建BOM详情弹框
    createBOMDetailDialog(row) {
      // 保存当前行数据，以便在弹框中使用
      this.currentRow = row;
      
      // 将Vue实例暴露给window对象，以便在弹窗中调用
      window.vueInstance = this;
      
      // 创建一个包含BOM信息、BOM配件和工艺路线标签页的弹框
      const dialogContent = this.createDialogContent(row);
      
      // 显示弹框
      ElMessageBox({
        title: 'BOM详情',
        message: dialogContent,
        dangerouslyUseHTMLString: true,
        customClass: 'bom-detail-dialog',
        showCancelButton: false,
        confirmButtonText: '关闭',
        callback: action => {
          if (action === 'confirm') {
            // 关闭弹框时的操作
            // 清除window上的Vue实例引用
            window.vueInstance = null;
          }
        }
      });
      
      // 绑定弹框事件处理程序
      this.$nextTick(() => {
        this.bindDialogEvents(row);
        
        // 加载BOM详情数据
        this.loadBOMDetailData(row);
      });
    },
    
    // 创建弹框内容
    createDialogContent(row) {
      // 创建一个包含BOM信息、BOM配件和工艺路线标签页的HTML
      return `
        <div class="bom-detail-container" style="min-height: 500px; width: 100%;">
          <div class="bom-header" style="margin-bottom: 20px;">
            <h2>${row.BOMReportTitle || '新产品新产品新产品BOM'}</h2>
            <div class="bom-info" style="display: flex; justify-content: space-between; margin-bottom: 10px;">
              <span>创建人: ${row.CreatorName || '赵五六'}</span>
              <span>创建时间: ${row.CreateDate ? new Date(row.CreateDate).toLocaleString() : '2025-06-09 16:18:16'}</span>
              <span>最后修改人: ${row.ModifierName || '赵五六'}</span>
              <span>修改时间: ${row.ModifyDate ? new Date(row.ModifyDate).toLocaleString() : '2022-06-07 19:49:12'}</span>
            </div>
          </div>
          
          <div class="bom-tabs">
            <div class="tab-header" style="display: flex; border-bottom: 2px solid #409EFF; margin-bottom: 15px;">
              <div class="tab-item" id="tab-info" style="padding: 10px 20px; cursor: pointer; background-color: #409EFF; color: white;">BOM信息</div>
              <div class="tab-item" id="tab-parts" style="padding: 10px 20px; cursor: pointer;">BOM配件</div>
              <div class="tab-item" id="tab-process" style="padding: 10px 20px; cursor: pointer;">工艺流程</div>
              <div class="tab-item" id="tab-operation" style="padding: 10px 20px; cursor: pointer;">操作记录</div>
            </div>
            
            <div class="tab-content">
              <div id="content-info" class="tab-pane" style="display: block;">
                <!-- BOM基本信息内容 -->
                <div class="bom-basic-info" style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                  <div class="info-item">
                    <span class="label" style="font-weight: bold;">BOM编号:</span>
                    <span class="value" id="bom-number">${row.BomNumber || 'BOM0000457'}</span>
                  </div>
                  <div class="info-item">
                    <span class="label" style="font-weight: bold;">BOM主题:</span>
                    <span class="value" id="bom-title">${row.BOMReportTitle || '产品lampBOM'}</span>
                  </div>
                  <div class="info-item">
                    <span class="label" style="font-weight: bold;">默认BOM:</span>
                    <span class="value" id="is-default">${row.IsDefaultBOM === 1 ? '是' : '否'}</span>
                  </div>
                  <div class="info-item">
                    <span class="label" style="font-weight: bold;">版本:</span>
                    <span class="value" id="bom-version">${row.Version || '1.1'}</span>
                  </div>
                  <div class="info-item">
                    <span class="label" style="font-weight: bold;">成品类型:</span>
                    <span class="value" id="product-type">${row.ArtifactType === 1 ? '类型一' : '类型二'}</span>
                  </div>
                  <div class="info-item">
                    <span class="label" style="font-weight: bold;">成品名称:</span>
                    <span class="value" id="product-name">${row.ProductName || 'lamp'}</span>
                  </div>
                  <div class="info-item">
                    <span class="label" style="font-weight: bold;">日产量:</span>
                    <span class="value" id="output">${row.Output || '50'}</span>
                  </div>
                  <div class="info-item">
                    <span class="label" style="font-weight: bold;">当前库存:</span>
                    <span class="value" id="current-stock">500</span>
                  </div>
                  <div class="info-item">
                    <span class="label" style="font-weight: bold;">预估成本:</span>
                    <span class="value" id="estimated-cost">${row.EstimatedCost || '8,000'}</span>
                  </div>
                  <div class="info-item" style="grid-column: span 2;">
                    <span class="label" style="font-weight: bold;">备注:</span>
                    <span class="value" id="remark">${row.Remark || ''}</span>
                  </div>
                  <div class="info-item" style="grid-column: span 2;">
                    <span class="label" style="font-weight: bold;">库存详情:</span>
                    <div class="stock-info" style="margin-top: 10px;">
                      <div>本地: 60</div>
                      <div>仓库二: 0</div>
                      <div>仓库三: 0</div>
                      <div>物料仓库一: 0</div>
                      <div>新产品仓库: 0</div>
                    </div>
                  </div>
                </div>
              </div>
              
              <div id="content-parts" class="tab-pane" style="display: none;">
                <!-- BOM配件内容 -->
                <div class="bom-parts">
                  <div class="toolbar" style="margin-bottom: 10px;">
                    <button id="export-parts" style="padding: 5px 10px; background-color: #409EFF; color: white; border: none; border-radius: 4px; cursor: pointer;">导出</button>
                  </div>
                  <table id="parts-table" style="width: 100%; border-collapse: collapse;">
                    <thead>
                      <tr style="background-color: #f2f2f2;">
                        <th style="padding: 8px; border: 1px solid #ddd;">序号</th>
                        <th style="padding: 8px; border: 1px solid #ddd;">物品编号</th>
                        <th style="padding: 8px; border: 1px solid #ddd;">物品名称</th>
                        <th style="padding: 8px; border: 1px solid #ddd;">规格型号</th>
                        <th style="padding: 8px; border: 1px solid #ddd;">单位</th>
                        <th style="padding: 8px; border: 1px solid #ddd;">品牌</th>
                        <th style="padding: 8px; border: 1px solid #ddd;">配件数量</th>
                        <th style="padding: 8px; border: 1px solid #ddd;">损耗率</th>
                        <th style="padding: 8px; border: 1px solid #ddd;">当前库存</th>
                        <th style="padding: 8px; border: 1px solid #ddd;">可供生产</th>
                        <th style="padding: 8px; border: 1px solid #ddd;">操作</th>
                      </tr>
                    </thead>
                    <tbody id="parts-body">
                      <!-- 配件数据将通过JavaScript动态添加 -->
                      <tr>
                        <td colspan="11" style="text-align: center; padding: 20px;">加载中...</td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>
              
              <div id="content-process" class="tab-pane" style="display: none;">
                <!-- 工艺流程内容 -->
                <div class="bom-process">
                  <div class="toolbar" style="margin-bottom: 10px;">
                    <button id="export-process" style="padding: 5px 10px; background-color: #409EFF; color: white; border: none; border-radius: 4px; cursor: pointer;">导出</button>
                  </div>
                  <table id="process-table" style="width: 100%; border-collapse: collapse;">
                    <thead>
                      <tr style="background-color: #f2f2f2;">
                        <th style="padding: 8px; border: 1px solid #ddd;">序号</th>
                        <th style="padding: 8px; border: 1px solid #ddd;">工序编码</th>
                        <th style="padding: 8px; border: 1px solid #ddd;">工序名称</th>
                        <th style="padding: 8px; border: 1px solid #ddd;">加工顺序</th>
                        <th style="padding: 8px; border: 1px solid #ddd;">工艺流程</th>
                        <th style="padding: 8px; border: 1px solid #ddd;">负责人</th>
                        <th style="padding: 8px; border: 1px solid #ddd;">部门</th>
                        <th style="padding: 8px; border: 1px solid #ddd;">单位工作量</th>
                        <th style="padding: 8px; border: 1px solid #ddd;">备注</th>
                      </tr>
                    </thead>
                    <tbody id="process-body">
                      <!-- 工艺流程数据将通过JavaScript动态添加 -->
                      <tr>
                        <td colspan="9" style="text-align: center; padding: 20px;">加载中...</td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>
              
              <div id="content-operation" class="tab-pane" style="display: none;">
                <!-- 操作记录内容 -->
                <div class="operation-log">
                  <table id="operation-table" style="width: 100%; border-collapse: collapse;">
                    <thead>
                      <tr style="background-color: #f2f2f2;">
                        <th style="padding: 8px; border: 1px solid #ddd;">序号</th>
                        <th style="padding: 8px; border: 1px solid #ddd;">操作类型</th>
                        <th style="padding: 8px; border: 1px solid #ddd;">操作人</th>
                        <th style="padding: 8px; border: 1px solid #ddd;">操作时间</th>
                        <th style="padding: 8px; border: 1px solid #ddd;">操作内容</th>
                      </tr>
                    </thead>
                    <tbody id="operation-body">
                      <!-- 操作记录数据将通过JavaScript动态添加 -->
                      <tr>
                        <td colspan="5" style="text-align: center; padding: 20px;">加载中...</td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <style>
          .bom-detail-dialog .el-message-box__content {
            overflow: auto;
            max-height: 80vh;
          }
          
          .bom-detail-dialog .el-message-box {
            width: 120%;
            max-width: 2000px;
          }
        </style>
      `;
    },
    
    // 在弹框显示后绑定事件处理程序
    bindDialogEvents(row) {
      console.log('开始绑定弹框事件处理程序');
      
      // 确保DOM元素已经加载完成
      setTimeout(() => {
        try {
          // 标签页切换逻辑
          const tabItems = document.querySelectorAll('.tab-item');
          if (tabItems && tabItems.length > 0) {
            console.log('找到标签页元素，绑定点击事件');
            
            tabItems.forEach(tab => {
              tab.addEventListener('click', function() {
                console.log('标签页点击:', this.id);
                
                // 移除所有标签页的活动状态
                document.querySelectorAll('.tab-item').forEach(t => {
                  t.style.backgroundColor = '';
                  t.style.color = '';
                });
                
                // 隐藏所有内容
                document.querySelectorAll('.tab-pane').forEach(content => {
                  content.style.display = 'none';
                });
                
                // 激活当前标签页
                this.style.backgroundColor = '#409EFF';
                this.style.color = 'white';
                
                // 显示对应内容
                const contentId = this.id.replace('tab-', 'content-');
                const contentElement = document.getElementById(contentId);
                if (contentElement) {
                  contentElement.style.display = 'block';
                  console.log('显示内容:', contentId);
                } else {
                  console.error('未找到内容元素:', contentId);
                }
              });
            });
          } else {
            console.error('未找到标签页元素');
          }
          
          // 导出按钮事件
          const exportPartsBtn = document.getElementById('export-parts');
          if (exportPartsBtn) {
            console.log('找到导出配件按钮，绑定点击事件');
            exportPartsBtn.addEventListener('click', function() {
              console.log('点击导出BOM配件按钮');
              // 调用导出BOM配件方法
              if (window.vueInstance) {
                window.vueInstance.exportBOMParts(row.BomId);
              } else {
                console.error('未找到Vue实例');
              }
            });
          } else {
            console.error('未找到导出配件按钮');
          }
          
          const exportProcessBtn = document.getElementById('export-process');
          if (exportProcessBtn) {
            console.log('找到导出工艺流程按钮，绑定点击事件');
            exportProcessBtn.addEventListener('click', function() {
              console.log('点击导出工艺流程按钮');
              // 调用导出工艺流程方法
              if (window.vueInstance) {
                window.vueInstance.exportBOMProcess(row.BomId);
              } else {
                console.error('未找到Vue实例');
              }
            });
          } else {
            console.error('未找到导出工艺流程按钮');
          }
          
          console.log('弹框事件处理程序绑定完成');
        } catch (error) {
          console.error('绑定事件处理程序出错:', error);
        }
      }, 500); // 延迟500毫秒确保DOM已加载
    },
    
    // 加载BOM详情数据
    loadBOMDetailData(row) {
      console.log('开始加载BOM详情数据，当前行数据:', row);
      
      // 加载BOM配件数据
      this.loadBOMParts(row.BomId);
      
      // 加载工艺流程数据
      this.loadBOMProcess(row.BomId);
      
      // 加载操作记录
      this.loadOperationLog(row.BomId);
    },
    
    // 加载BOM配件
    loadBOMParts(bomId) {
      console.log('加载BOM配件数据，BomId:', bomId);
      
      // 检查是否需要使用模拟数据
      const useMockData = true; // 如果后端API未实现，设置为true
      
      if (useMockData) {
        // 使用模拟数据
        console.log('使用模拟BOM配件数据');
        const mockData = {
          rows: [
            { 
              MaterialCode: 'WLBH559', 
              MaterialName: '物料0545', 
              MaterialModel: 'GL-1000-TIMEBOND',
              UnitName: '瓶',
              Brand: '五毒牌',
              Quantity: 5,
              LossRate: '10%'
            },
            { 
              MaterialCode: 'WLBH559', 
              MaterialName: '物料0545', 
              MaterialModel: 'GL-1000-TIMEBOND',
              UnitName: '瓶',
              Brand: '五毒牌',
              Quantity: 5,
              LossRate: '10%'
            },
            { 
              MaterialCode: 'WLBH559', 
              MaterialName: '物料0545', 
              MaterialModel: 'GL-1000-TIMEBOND',
              UnitName: '瓶',
              Brand: '五毒牌',
              Quantity: 5,
              LossRate: '10%'
            },
            { 
              MaterialCode: 'WLBH559', 
              MaterialName: '物料0545', 
              MaterialModel: 'GL-1000-TIMEBOND',
              UnitName: '瓶',
              Brand: '五毒牌',
              Quantity: 5,
              LossRate: '10%'
            },
            { 
              MaterialCode: 'WLBH559', 
              MaterialName: '物料0545', 
              MaterialModel: 'GL-1000-TIMEBOND',
              UnitName: '瓶',
              Brand: '五毒牌',
              Quantity: 5,
              LossRate: '10%'
            }
          ]
        };
        
        // 渲染配件表格
        const partsBody = document.getElementById('parts-body');
        if (partsBody) {
          console.log('找到parts-body元素，开始渲染模拟数据');
          let html = '';
          mockData.rows.forEach((item, index) => {
            html += `
              <tr>
                <td style="padding: 8px; border: 1px solid #ddd;">${index + 1}</td>
                <td style="padding: 8px; border: 1px solid #ddd;">${item.MaterialCode}</td>
                <td style="padding: 8px; border: 1px solid #ddd;">${item.MaterialName}</td>
                <td style="padding: 8px; border: 1px solid #ddd;">${item.MaterialModel}</td>
                <td style="padding: 8px; border: 1px solid #ddd;">${item.UnitName}</td>
                <td style="padding: 8px; border: 1px solid #ddd;">${item.Brand}</td>
                <td style="padding: 8px; border: 1px solid #ddd;">${item.Quantity}</td>
                <td style="padding: 8px; border: 1px solid #ddd;">${item.LossRate}</td>
                <td style="padding: 8px; border: 1px solid #ddd;">5</td>
                <td style="padding: 8px; border: 1px solid #ddd;">5</td>
                <td style="padding: 8px; border: 1px solid #ddd;">
                  <a href="javascript:void(0)" style="color: #409EFF;">创建子BOM</a>
                </td>
              </tr>
            `;
          });
          partsBody.innerHTML = html;
          console.log('BOM配件模拟数据渲染完成');
        } else {
          console.error('未找到parts-body元素');
        }
        
        return;
      }
      
      // 使用真实API
      this.http.post("api/BomMaster/getTable1Data", {
        wheres: [{ name: "BomId", value: bomId }]
      }, true).then(res => {
        console.log('BOM配件数据返回结果:', res);
        
        if (res && res.rows && res.rows.length > 0) {
          // 渲染配件表格
          const partsBody = document.getElementById('parts-body');
          if (partsBody) {
            console.log('找到parts-body元素，开始渲染数据');
            let html = '';
            res.rows.forEach((item, index) => {
              html += `
                <tr>
                  <td style="padding: 8px; border: 1px solid #ddd;">${index + 1}</td>
                  <td style="padding: 8px; border: 1px solid #ddd;">${item.MaterialCode || 'WLBH559'}</td>
                  <td style="padding: 8px; border: 1px solid #ddd;">${item.MaterialName || '物料0545'}</td>
                  <td style="padding: 8px; border: 1px solid #ddd;">${item.MaterialModel || 'GL-1000-TIMEBOND'}</td>
                  <td style="padding: 8px; border: 1px solid #ddd;">${item.UnitName || '瓶'}</td>
                  <td style="padding: 8px; border: 1px solid #ddd;">${item.Brand || '五毒牌'}</td>
                  <td style="padding: 8px; border: 1px solid #ddd;">${item.Quantity || '5'}</td>
                  <td style="padding: 8px; border: 1px solid #ddd;">${item.LossRate || '10%'}</td>
                  <td style="padding: 8px; border: 1px solid #ddd;">5</td>
                  <td style="padding: 8px; border: 1px solid #ddd;">5</td>
                  <td style="padding: 8px; border: 1px solid #ddd;">
                    <a href="javascript:void(0)" style="color: #409EFF;">创建子BOM</a>
                  </td>
                </tr>
              `;
            });
            partsBody.innerHTML = html;
            console.log('BOM配件数据渲染完成');
          } else {
            console.error('未找到parts-body元素');
          }
        } else {
          console.warn('BOM配件数据为空或格式不正确');
          // 如果没有数据，显示空状态
          const partsBody = document.getElementById('parts-body');
          if (partsBody) {
            partsBody.innerHTML = '<tr><td colspan="11" style="text-align: center; padding: 20px;">暂无数据</td></tr>';
          }
        }
      }).catch(err => {
        console.error('加载BOM配件数据出错:', err);
      });
    },
    
    // 加载工艺流程
    loadBOMProcess(bomId) {
      console.log('加载工艺流程数据，BomId:', bomId);
      
      // 检查是否需要使用模拟数据
      const useMockData = true; // 如果后端API未实现，设置为true
      
      if (useMockData) {
        // 使用模拟数据
        console.log('使用模拟工艺流程数据');
        const mockData = {
          rows: [
            { 
              RouteCode: '7820864', 
              RouteName: '设备生产工序', 
              ResponsiblePerson: '周瑜',
              Department: '生产部门一',
              UnitWorkload: '90',
              Remark: ''
            },
            { 
              RouteCode: '5786931', 
              RouteName: '食品生产工序', 
              ResponsiblePerson: '周瑜',
              Department: '生产部门一',
              UnitWorkload: '90',
              Remark: ''
            },
            { 
              RouteCode: '8518691', 
              RouteName: '工序分类16', 
              ResponsiblePerson: '周瑜',
              Department: '生产部门一',
              UnitWorkload: '90',
              Remark: ''
            },
            { 
              RouteCode: '6576642', 
              RouteName: '工序分类17', 
              ResponsiblePerson: '周瑜',
              Department: '生产部门一',
              UnitWorkload: '90',
              Remark: ''
            },
            { 
              RouteCode: '6081578', 
              RouteName: '工序分类18', 
              ResponsiblePerson: '周瑜',
              Department: '生产部门一',
              UnitWorkload: '90',
              Remark: ''
            }
          ]
        };
        
        // 渲染工艺流程表格
        const processBody = document.getElementById('process-body');
        if (processBody) {
          console.log('找到process-body元素，开始渲染模拟数据');
          let html = '';
          mockData.rows.forEach((item, index) => {
            html += `
              <tr>
                <td style="padding: 8px; border: 1px solid #ddd;">${index + 1}</td>
                <td style="padding: 8px; border: 1px solid #ddd;">${item.RouteCode}</td>
                <td style="padding: 8px; border: 1px solid #ddd;">${item.RouteName}</td>
                <td style="padding: 8px; border: 1px solid #ddd;">${index + 1}</td>
                <td style="padding: 8px; border: 1px solid #ddd;">新产品工艺流程</td>
                <td style="padding: 8px; border: 1px solid #ddd;">${item.ResponsiblePerson}</td>
                <td style="padding: 8px; border: 1px solid #ddd;">${item.Department}</td>
                <td style="padding: 8px; border: 1px solid #ddd;">${item.UnitWorkload}</td>
                <td style="padding: 8px; border: 1px solid #ddd;">${item.Remark}</td>
              </tr>
            `;
          });
          processBody.innerHTML = html;
          console.log('工艺流程模拟数据渲染完成');
        } else {
          console.error('未找到process-body元素');
        }
        
        return;
      }
      
      // 使用真实API
      this.http.post("api/BomMaster/getTable2Data", {
        wheres: [{ name: "BomId", value: bomId }]
      }, true).then(res => {
        console.log('工艺流程数据返回结果:', res);
        
        if (res && res.rows && res.rows.length > 0) {
          // 渲染工艺流程表格
          const processBody = document.getElementById('process-body');
          if (processBody) {
            console.log('找到process-body元素，开始渲染数据');
            let html = '';
            res.rows.forEach((item, index) => {
              html += `
                <tr>
                  <td style="padding: 8px; border: 1px solid #ddd;">${index + 1}</td>
                  <td style="padding: 8px; border: 1px solid #ddd;">${item.RouteCode || (7820864 + index)}</td>
                  <td style="padding: 8px; border: 1px solid #ddd;">${item.RouteName || '设备生产工序'}</td>
                  <td style="padding: 8px; border: 1px solid #ddd;">${index + 1}</td>
                  <td style="padding: 8px; border: 1px solid #ddd;">新产品工艺流程</td>
                  <td style="padding: 8px; border: 1px solid #ddd;">${item.ResponsiblePerson || '周瑜'}</td>
                  <td style="padding: 8px; border: 1px solid #ddd;">${item.Department || '生产部门一'}</td>
                  <td style="padding: 8px; border: 1px solid #ddd;">${item.UnitWorkload || '90'}</td>
                  <td style="padding: 8px; border: 1px solid #ddd;">${item.Remark || ''}</td>
                </tr>
              `;
            });
            processBody.innerHTML = html;
            console.log('工艺流程数据渲染完成');
          } else {
            console.error('未找到process-body元素');
          }
        } else {
          console.warn('工艺流程数据为空或格式不正确');
          // 如果没有数据，显示空状态
          const processBody = document.getElementById('process-body');
          if (processBody) {
            processBody.innerHTML = '<tr><td colspan="9" style="text-align: center; padding: 20px;">暂无数据</td></tr>';
          }
        }
      }).catch(err => {
        console.error('加载工艺流程数据出错:', err);
      });
    },
    
    // 加载操作记录
    loadOperationLog(bomId) {
      // 模拟操作记录数据
      const operationData = [
        { type: '创建', user: '赵五六', time: '2025-06-09 16:18:16', content: '创建BOM' },
        { type: '修改', user: '赵五六', time: '2022-06-07 19:49:12', content: '修改BOM信息' }
      ];
      
      const operationBody = document.getElementById('operation-body');
      if (operationBody) {
        let html = '';
        operationData.forEach((item, index) => {
          html += `
            <tr>
              <td style="padding: 8px; border: 1px solid #ddd;">${index + 1}</td>
              <td style="padding: 8px; border: 1px solid #ddd;">${item.type}</td>
              <td style="padding: 8px; border: 1px solid #ddd;">${item.user}</td>
              <td style="padding: 8px; border: 1px solid #ddd;">${item.time}</td>
              <td style="padding: 8px; border: 1px solid #ddd;">${item.content}</td>
            </tr>
          `;
        });
        operationBody.innerHTML = html;
      }
    },
    
    // 导出BOM配件
    exportBOMParts(bomId) {
      this.http.post("api/BomMaster/exportTable1Data", {
        wheres: [{ name: "BomId", value: bomId }]
      }, true).then(res => {
        if (res && res.status) {
          // 下载导出的文件
          window.open(res.data);
        } else {
          ElMessage.error('导出失败');
        }
      });
    },
    
    // 导出工艺流程
    exportBOMProcess(bomId) {
      this.http.post("api/BomMaster/exportTable2Data", {
        wheres: [{ name: "BomId", value: bomId }]
      }, true).then(res => {
        if (res && res.status) {
          // 下载导出的文件
          window.open(res.data);
        } else {
          ElMessage.error('导出失败');
        }
      });
    }
  }
};
export default extension;
